package com.dehui.traders.ui.stockdetail;

import android.content.Context;
import android.databinding.ObservableField;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.dehui.traders.R;
import com.dehui.traders.bean.Announcement;
import com.dehui.traders.bean.BaseListResponse;
import com.dehui.traders.bean.BaseResponse;
import com.dehui.traders.bean.FinancialData;
import com.dehui.traders.bean.OptionalCodeRank;
import com.dehui.traders.bean.RealtimeQuote;
import com.dehui.traders.ui.stockdetail.bean.LabelTabel;
import com.dehui.traders.ui.stockdetail.bean.StockCapital;
import com.dehui.traders.config.Preferences;
import com.dehui.traders.service.CallListener;
import com.dehui.traders.service.NetImpl;
import com.dehui.traders.utils.UserHelp;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.ToastUtils;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by hqq on 18.4.2.
 */

public class StocksDetailViewModel extends BaseViewModel{

    private StocksDetailActivity activity;
    private String name;
    private String code;
    private String market;
    private int mType = 0;

    public ObservableField<Integer> topPbVisibile = new ObservableField<>(View.GONE);

    public ObservableField<Integer> topRefreshVisible = new ObservableField<>(View.VISIBLE);

    public ObservableField<Integer> addOptionalVisiable = new ObservableField<>(View.VISIBLE);

    public ObservableField<Integer> deleteOptionalVisiable = new ObservableField<>(View.GONE);

    public ObservableField<String> stocksDetailName = new ObservableField<>();

    public ObservableField<String> stocksCode = new ObservableField<>();

    public ObservableField<String> leftName = new ObservableField<>();


    public BindingCommand backOnclick = new BindingCommand(()->{
        activity.finish();
    });

    public BindingCommand refreshOnClick = new BindingCommand(()->{
        topRefreshVisible.set(View.GONE);
        topPbVisibile.set(View.VISIBLE);
        reFreshData();
    });

    /**
     * 添加到自选股
     */
    public BindingCommand addOptionalOnClick = new BindingCommand(()->{
        if (!UserHelp.getIsLogin(context))
            return;
        Call<BaseResponse<String>> call = NetImpl.saveCode(code,market, UserHelp.getUserId(), "0",name, "0");
        call.enqueue(new CallListener<BaseResponse<String>>() {
            @Override
            public void _onResponse(Response<BaseResponse<String>> response) {
                BaseResponse<String> baseResponse = response.body();
                if (baseResponse.status == 200){
                    updateOptionCodeFile();
                    addOptionalVisiable.set(View.GONE);
                    deleteOptionalVisiable.set(View.VISIBLE);
                }else{
                    ToastUtils.showShort(R.string.add_failed);
                }
            }

            @Override
            public void _onFailure() {
                ToastUtils.showShort(R.string.add_failed);
            }
        });
    });

    /**
     * 删除自选股
     */
    public BindingCommand deleteOptionalOnClick = new BindingCommand(()->{

        Call<BaseResponse<String>> call = NetImpl.deleteCode(code, market);
        call.enqueue(new CallListener<BaseResponse<String>>() {
            @Override
            public void _onResponse(Response<BaseResponse<String>> response) {

            }

            @Override
            public void _onFailure() {
                ToastUtils.showShort("删除失败");
            }
        });
        String myOpitonCode = Preferences.getMyOpitonCode();
        List<OptionalCodeRank> locationList = new Gson().fromJson(myOpitonCode, new TypeToken<List<OptionalCodeRank>>() {}.getType());
        for (int i = 0; i < locationList.size(); i++){
            OptionalCodeRank codeRank = locationList.get(i);
            if (code.equals(codeRank.code)){
                locationList.remove(i);
                break;
            }
        }
        Preferences.saveMyOpitonCode(new Gson().toJson(locationList));
        addOptionalVisiable.set(View.VISIBLE);
        deleteOptionalVisiable.set(View.GONE);
    });

    public StocksDetailViewModel(Context context, StocksDetailActivity activity, String name, String code, String market, int mType) {
        super(context);
        this.activity = activity;
        this.name = name;
        this.code = code;
        this.market = market;
        this.mType = mType;
        leftName.set(activity.getmLeftName());
        stocksDetailName.set(name);
        stocksCode.set(code);
        if (mType == 0){
            isMyOptional();
        }else{
            addOptionalVisiable.set(View.GONE);
            deleteOptionalVisiable.set(View.GONE);
        }
    }



    private void updateOptionCodeFile() {
        String myOpitonCode = Preferences.getMyOpitonCode();
        List<OptionalCodeRank> codeList = null;
        try {
            codeList =new Gson().fromJson(myOpitonCode, new TypeToken<List<OptionalCodeRank>>() {}.getType());
        }catch (Exception e){
            codeList = new ArrayList<>();
        }

        codeList.add(0,new OptionalCodeRank(name,code,market,0));
        String codestr = new Gson().toJson(codeList);
        Preferences.saveMyOpitonCode(codestr);
    }

    private void isMyOptional() {
        if(TextUtils.isEmpty(Preferences.getToken()))
            return;

        String myOpitonCode = Preferences.getMyOpitonCode();
        try {
            List<OptionalCodeRank> list =new Gson().fromJson(myOpitonCode, new TypeToken<List<OptionalCodeRank>>() {}.getType());
            if (list == null)
                return;
            for (OptionalCodeRank item : list){
                if (item.code.equals(code)){
                    addOptionalVisiable.set(View.GONE);
                    deleteOptionalVisiable.set(View.VISIBLE);
                }
            }
        }catch (Exception e){

        }
    }


    public void getData() {
        getRealTime();

    }

    private void getLabelTabel() {
        Call<BaseListResponse<LabelTabel>> call = NetImpl.getLabelTabel(market + code);
        call.enqueue(new CallListener<BaseListResponse<LabelTabel>>() {
            @Override
            public void _onResponse(Response<BaseListResponse<LabelTabel>> response) {
                BaseListResponse<LabelTabel> body = response.body();
                if (body.status == 200){
                    activity.initLabelTabel(body.result);
                }
            }

            @Override
            public void _onFailure() {

            }
        });
    }


    /**
     * 资金流向
     */
    private void getStockcapital() {
        Call<BaseListResponse<StockCapital>> call = NetImpl.stockCapital();
        call.enqueue(new CallListener<BaseListResponse<StockCapital>>() {
            @Override
            public void _onResponse(Response<BaseListResponse<StockCapital>> response) {
                BaseListResponse<StockCapital> body = response.body();
                if (body.status == 200){
                    activity.initStockCaptial(body.result);
                }
            }

            @Override
            public void _onFailure() {

            }
        });
    }

    /**
     * 查询财务信息
     */
    private void queryFinancial() {
        Call<BaseListResponse<FinancialData[]>> call = NetImpl.queryFinancialData(code);
        call.enqueue(new CallListener<BaseListResponse<FinancialData[]>>() {
            @Override
            public void _onResponse(Response<BaseListResponse<FinancialData[]>> response) {
                BaseListResponse<FinancialData[]> body = response.body();
                if (body.status == 200){
                    List<FinancialData[]> financialData = body.result;
                    dealFinancial(financialData);
                }
            }

            @Override
            public void _onFailure() {

            }
        });
    }

    /**
     * 股东信息
     */
    private void queryShareHolder() {
        Call<BaseListResponse<FinancialData[]>> call = NetImpl.querySahreHolderData(code);
        call.enqueue(new CallListener<BaseListResponse<FinancialData[]>>() {
            @Override
            public void _onResponse(Response<BaseListResponse<FinancialData[]>> response) {

            }

            @Override
            public void _onFailure() {

            }
        });
    }

    private void dealFinancial(List<FinancialData[]> financialData) {

        String[] f1Titles = new String[]{"应收账款","其他应收款","应收利息","流动资产合计","非流动资产合计","固定资产",
                "资产总计","应付账款","其他应付款","其他流动负债"};
        String[] f2Ttiles = new String[]{"营业总收入","营业利润","投资收益","营业外收入","其他收益","利润总额","净利润",
                "归属于母公司"};
        String[] f3Titles = new String[]{"经营活动现金流入小计","经营活动现金流出小计","经营活动产生的现金流量净额","投资活动现金流入小计",
                "投资活动现金流出小计","投资活动产生的现金流量净额","筹资活动现金流入小计","筹资活动现金流出小计","筹资活动产生的现金流量净额"};
        FinancialData f1 = null; //利润表
        FinancialData f2 = null; //资产负债表
        FinancialData f3 = null; //主要指标

        for (int i=0; i < financialData.size(); i++){
            FinancialData[] data = financialData.get(i);
            for (int j=0; j < data.length; j++){
                FinancialData datum = data[j];
                if (datum.getF003V().equals("母公司本期")){

                    String status = datum.getSTATUS();
                    if (status.equals("1")){
                        f1 = datum;
                    }else if (status.equals("2")){
                        f2 = datum;
                    }else if (status.equals("3")){
                        f3 = datum;
                    }else if (status.equals("4")){
                    }
                }
            }

        }

        activity.initFinancial1(f1Titles,f1,f2Ttiles,f2,f3Titles,f3);
    }


    /**
     * 查询公告消息
     */
    private void queryAnnouncement() {
        Call<BaseListResponse<Announcement>> call = NetImpl.queryAnnouncement(code);
        call.enqueue(new CallListener<BaseListResponse<Announcement>>() {
            @Override
            public void _onResponse(Response<BaseListResponse<Announcement>> response) {
                BaseListResponse<Announcement> body = response.body();
                if (body.status == 200){
                    List<Announcement> announcementList = body.result;
                    activity.updateAnnouncementList(announcementList);
                }
            }

            @Override
            public void _onFailure() {

            }
        });
    }

    public void reFreshData(){
        getRealTime();
    }

    private void getRealTime() {
        List<OptionalCodeRank> list = new ArrayList<>();
        list.add(new OptionalCodeRank(name,market + code,"",0));
        String s = new Gson().toJson(list);
        Log.e("Hqq",s);
        Call<BaseListResponse<RealtimeQuote>> call = NetImpl.getRealtimeQuote(list);
        call.enqueue(new CallListener<BaseListResponse<RealtimeQuote>>() {
            @Override
            public void _onResponse(Response<BaseListResponse<RealtimeQuote>> response) {
                BaseListResponse<RealtimeQuote> realtimeQuoteBaseListResponse = response.body();
                if (realtimeQuoteBaseListResponse.status == 200){
                    List<RealtimeQuote> realtimeQuoteList = realtimeQuoteBaseListResponse.result;
                    RealtimeQuote realtimeQuote = realtimeQuoteList.get(0);
                    activity.initTopData(realtimeQuote);
                    activity.initFiveView();
                    if (mType == 0){
                        getLabelTabel();
                    }else {
                        getStockcapital();
                    }
                }

                topRefreshVisible.set(View.VISIBLE);
                topPbVisibile.set(View.GONE);
            }

            @Override
            public void _onFailure() {
                ToastUtils.showShort("网络异常");

                topRefreshVisible.set(View.VISIBLE);
                topPbVisibile.set(View.GONE);
            }
        });
    }


}
